<?php
namespace System\Controller;
use Common\Controller\AdminbaseController;
class LoginController extends AdminbaseController {

	public function _initialize() {
		C(S('sp_dynamic_config'));//加载动态配置
	}

	//后台登陆界面
	public function login() {
		$admin_id=session('ADMIN_ID');
		if(!empty($admin_id)){//已经登录
			redirect(U("System/index/index"));
		}else{
			$site_admin_url_password =C("SP_SITE_ADMIN_URL_PASSWORD");
			$upw=session("__SP_UPW__");
			if(!empty($site_admin_url_password) && $upw!=$site_admin_url_password){
				redirect(__ROOT__."/");
			}else{
				session("__SP_ADMIN_LOGIN_PAGE_SHOWED_SUCCESS__",true);
				$this->display("login");
			}
		}
	}

	public function logout(){
		session('ADMIN_ID',null);
		redirect(__ROOT__."/");
	}

	public function dologin(){
		$login_page_showed_success=session("__SP_ADMIN_LOGIN_PAGE_SHOWED_SUCCESS__");
		if(!$login_page_showed_success){
			$this->error('login error!');
		}
		$name = I("post.username");
		if(empty($name)){
			$this->error('用户名或邮箱不能为空!');
		}
		$pass = I("post.password");
		if(empty($pass)){
			$this->error('密码不能为空!');
		}
		$verrify = I("post.verify");
		if(empty($verrify)){
			$this->error('验证码不能为空！');
		}
		//验证码
		if(!sp_check_verify_code()){
			$this->error('验证码错误！');
		}else{
			$user = D("SystemAdmin");
			if(strpos($name,"@")>0){//邮箱登陆
				$where['user_email']=$name;
			}else{
				$where['user_login']=$name;
			}

			$result = $user->where($where)->find();
			if(!empty($result) && $result['user_type']==1){
				if(sp_compare_password($pass,$result['user_pass'])){

					$role_user_model=M("SystemAdminRoleUser");

					$role_user_join = C('DB_PREFIX').'system_admin_role as b on a.role_id =b.id';

					$groups=$role_user_model->alias("a")->join($role_user_join)->where(array("user_id"=>$result["id"],"status"=>1))->getField("role_id",true);

					if( $result["id"]!=1 && ( empty($groups) || empty($result['user_status']) ) ){
						$this->error('用户已经被禁止！');
					}
					//登入成功页面跳转
					session('ADMIN_ID',$result["id"]);
					session('name',$result["user_login"]);
					$result['last_login_ip']=get_client_ip(0,true);
					$result['last_login_time']=date("Y-m-d H:i:s");
					$user->save($result);
					cookie("admin_username",$name,3600*24*30);
					$this->success('登录成功！',U("Index/index"));
				}else{
					$this->error('密码错误！');
				}
			}else{
				$this->error('用户名不存在！');
			}
		}
	}

}